import {BrowserWindow, ipcMain, Menu, MenuItem, MenuItemConstructorOptions} from "electron";

ipcMain.handle('menus:command', (event, key: string, x: number, y: number) => {
  const win = BrowserWindow.fromWebContents(event.sender)
  if (!win) return

  let menuTemplate: Array<(MenuItemConstructorOptions) | (MenuItem)> = []
  // 处理菜单命令
  switch (key) {
    case 'file':
      menuTemplate = getFileMenuTemplate(win)
      break
    case 'edit':
      menuTemplate = getEditMenuTemplate(win)
      break
    case 'view':
      menuTemplate = getViewMenuTemplate(win)
      break
  }

  if (menuTemplate && menuTemplate.length > 0) {
    const menu = Menu.buildFromTemplate(menuTemplate)
    if (menu) {
      menu.popup({ window: win, x, y })
    }
  }
})

function getFileMenuTemplate(win: BrowserWindow): Array<(MenuItemConstructorOptions) | (MenuItem)> {
  return [
    {
      label: '新建笔记',
      accelerator: 'CmdOrCtrl+N',
      click: () => {
        win.webContents.send('file-new')
      },
    },
    {
      label: '打开文件空间',
      accelerator: 'CmdOrCtrl+O',
      click: () => {
        win.webContents.send('file-open')
      },
    },
    {
      label: '另存为...',
      accelerator: 'CmdOrCtrl+Shift+S',
      click: () => {
        win.webContents.send('file-save-as')
      },
    },
    { type: 'separator' },
    {
      label: '设置',
      click: () => {
        // const settingWin = new BrowserWindow({
        //   title: '设置',
        //   parent: win,
        //   autoHideMenuBar: true,
        // })
        // if (VITE_DEV_SERVER_URL) {
        //   settingWin.loadURL(VITE_DEV_SERVER_URL + '/#/settings')
        // } else {
        //   // win.loadFile('dist/index.html')
        //   settingWin.loadFile(path.join(RENDERER_DIST, 'index.html/#/settings'))
        // }
        win.webContents.send('menu:file:setting')
      },
    },
    { type: 'separator' },
    {
      label: '退出',
      role: 'quit',
    },
  ]
}

function getEditMenuTemplate(win: BrowserWindow): Array<(MenuItemConstructorOptions) | (MenuItem)> {
  return [
    {
      label: '撤销',
      accelerator: 'CmdOrCtrl+Z',
      role: 'undo',
    },
    {
      label: '重做',
      accelerator: 'CmdOrCtrl+Y',
      role: 'redo',
    },
    { type: 'separator' },
    {
      label: '剪切',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
    },
    {
      label: '复制',
      accelerator: 'CmdOrCtrl+C',
      role: 'copy',
    },
    {
      label: '粘贴',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    },
  ]
}

function getViewMenuTemplate(win: BrowserWindow): Array<(MenuItemConstructorOptions) | (MenuItem)> {
  return [
    {
      label: '刷新',
      accelerator: 'CmdOrCtrl+R',
      click: () => {
        win.reload()
      },
    },
    {
      label: '开发者工具',
      accelerator: 'CmdOrCtrl+Shift+I',
      click: () => {
        win.webContents.toggleDevTools()
      },
    },
  ]
}
